import odoo from '@/odoo'

const Model = odoo.env('media.article')

export default {
  namespace: 'article',

  state: {
    list: [],
    record: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const {state} = payload
      const Model = odoo.env('media.article')
      const recs = yield Model.searchByState(state)
      const response = recs.look2()

      yield put({
        type: 'queryList',
        payload: Array.isArray(response) ? response : [],
      });
    },

    *create({payload}, { call, put }) {
      const { vals } = payload
      const record_ins = yield Model.create(vals)

      if (record_ins.id){
        const response = record_ins.look2()
        yield put({
          type: 'appendList',
          payload: Array.isArray(response) ? response : [],
        });
        yield put({
          type: 'view',
          payload: { id: record_ins.id },
        });

      }
    },


    *write({payload}, { call, put }) {
      const { id, vals } = payload
      const vals2 = {...vals }
      const record_ins = yield Model.write(id, vals2)

      if (record_ins.id){
        //const record = record_ins.look()
        yield put({
          type: 'view',
          payload: { id: record_ins.id },
        });
      }
    },


    *appendFetch({ payload }, { call, put }) {
      const recs = yield Model.search([])
      const response = recs.look2()
      yield put({
        type: 'appendList',
        payload: Array.isArray(response) ? response : [],
      });
    },

  },

  reducers: {
    view(state, { payload }) {
      const {id} = payload
      const rec = Model.view(id)

      return {
        ...state,
        record: rec.look()
      };
    },

    queryList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    appendList(state, action) {
      return {
        ...state,
        list: state.list.concat(action.payload),
      };
    },
  },
};
